﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace Pocahontas.Mvc.WebForms
{
    public class WebFormsSitecoreHelper<TModel>
    {
        private WebFormsHtmlHelper<TModel> _htmlHelper;
        private ISitecoreFieldMarkupStrategy _markupStrategy;

        public WebFormsSitecoreHelper(WebFormsHtmlHelper<TModel> htmlHelper, ISitecoreFieldMarkupStrategy markupStrategy)
        {
            _htmlHelper = htmlHelper;
            _markupStrategy = markupStrategy;
        }

        public IHtmlString FieldFor<TProperty>(Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
        {
            return FieldFor(expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private IHtmlString FieldFor<TProperty>(Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        {
            SitecoreFieldMetadata fieldMetadata = SitecoreFieldMetadata.FromLambdaExpression<TModel, TProperty>(expression, _htmlHelper.ViewData);

            SitecoreFieldAttributeDictionary fieldAttributes = SitecoreFieldAttributeDictionary.FromAttributes(htmlAttributes);

            ISitecoreFieldMarkup markup = _markupStrategy.GetFieldMarkup(fieldMetadata, fieldAttributes);

            return new HtmlString(markup.GetHtml(null));
        }
    }
}
